package Client;
import java.net.InetSocketAddress;
import java.nio.charset.Charset;

import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.transport.socket.nio.NioSocketConnector;

import Handler.ClientHandler;


public class Client {

	private String IP;
	private int PORT;
	private NioSocketConnector connector;
	private ConnectFuture cf;
	
	
	public Client()
	{
		this.IP = "127.0.0.1";
		this.PORT = 8093;
		this.connector = new NioSocketConnector();
	}
	
	public Client(String ip,int port)
	{
		this.IP = ip;
		this.PORT = port;
		this.connector = new NioSocketConnector();
	}
	
	public void SetFilter()
	{
		this.connector.getFilterChain().addLast("logger",new LoggingFilter());
		this.connector.getFilterChain().addLast("codec", new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("UTF-8"))));
		this.connector.setConnectTimeoutCheckInterval(30);
		this.connector.setHandler(new ClientHandler());
	}
	
	public void Connect() throws Exception
	{
        this.cf = this.connector.connect(new InetSocketAddress(this.IP,this.PORT));
        this.cf.awaitUninterruptibly();
	}
	
	public void Disconnect() throws Exception
	{
		this.cf.getSession().getCloseFuture().awaitUninterruptibly();
		this.connector.dispose();
	}
	
	public boolean SendString(String str) throws Exception
	{
	     this.cf.getSession().write(str);
	     return true;
	}
	
	
//	public static void main(String[] args) throws IOException
//	{
//		
////		NioSocketConnector connector = new NioSocketConnector();
////		connector.getFilterChain().addLast("logger",new LoggingFilter());
////		connector.getFilterChain().addLast("codec", new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("UTF-8"))));
////		connector.setConnectTimeoutCheckInterval(30);
////		connector.setHandler(new ClientHandler());
////		ConnectFuture cf = connector.connect(new InetSocketAddress(IP,PORT));
//		//cf.awaitUninterruptibly();
//		
//		
//		BufferedReader bufred = new BufferedReader(new InputStreamReader(System.in));
//		while(true)
//		{
//			String instring = bufred.readLine();
//			cf.getSession().write(instring);
//			if(instring.equals("quit"))
//			{
//				System.out.println("QUIT!");
//				break;
//			}
//		}
//		
//		
//		cf.getSession().getCloseFuture().awaitUninterruptibly();
//		connector.dispose();
//		
//		
	}
